<template>
  <div>
    <!-- 查询表单 -->
    <el-form :model="setPageInfo" :inline="true">
      <el-form-item label="昵称" label-width="60px">
        <el-input v-model="setPageInfo.nickname" placeholder="输入昵称"
                  @keyup.enter.native="onSubmit"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 增加删除按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 关键数据表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%; text-align: center;" height="480"
              ref="multipleTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column fixed prop="avater" label="头像" width="110">
        <template slot-scope="scope">
          <el-avatar :size="60" :src="scope.row.avater">
            <img v-if="scope.row.avater" :src="scope.row.avater"/>
            <img v-else src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="呢称" width="120">
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="80" :formatter="formatterSex">
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="160">
      </el-table-column>
      <el-table-column prop="birthday" label="出生年月" width="120">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="localtion" label="地区" width="180">
      </el-table-column>
      <el-table-column prop="sign" label="个性签名" width="200">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180">
      </el-table-column>

      <el-table-column prop="isDisable" label="是否禁用" width="120" :formatter="formatterIsDisable">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="handleChange(scope.row)" type="text" size="mini">编辑</el-button>
          <el-button type="text" @click="handleDeleteRow(scope.row)" size="mini">删除</el-button>
          <el-button type="text" @click="resetPassword(scope.row)" size="mini">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
                   :current-page="setPageInfo.currentPage" :page-sizes="[5,10,15]" :page-size="setPageInfo.pageSize"
                   layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalCount">
    </el-pagination>

    <!-- 新增or编辑 -->
    <div>
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="addData" :inline="true" :rules="rules" ref="ruleForm">
          <el-col>
            <el-form-item label="头像" :label-width="formLabelWidth">
              <!-- 头像修改 -->
              <el-upload action="http://lzyzone.top/uploadimage/image/upload/ly" list-type="text" :limit="1"
                         :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                         :on-success="handleAvatarSuccess"
                         :on-exceed="handleExceed" :before-upload="beforeAvatarUpload">
                <img v-if="addData.avater" :src="addData.avater" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname">
            <el-input v-model="addData.nickname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
            <el-radio v-model="addData.sex" :label="1">男</el-radio>
            <el-radio v-model="addData.sex" :label="0">女</el-radio>
          </el-form-item>
          <el-form-item label="出生年月" :label-width="formLabelWidth" prop="birthday">
            <!-- 时间选择器 -->
            <el-date-picker v-model="addData.birthday" align="right" type="date" placeholder="选择日期"
                            :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="addData.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话号码" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="addData.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地区" :label-width="formLabelWidth">
            <el-input v-model="addData.localtion" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="是否禁用" :label-width="formLabelWidth">
            <el-switch v-model="addData.isDisable" active-value="1" inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="个性签名" :label-width="formLabelWidth">
            <el-input v-model="addData.sign" type="textarea" autocomplete="off"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex';

  import member from "../../api/member";

  import {
    formatDate,
    format
  } from '../../api/index.js'

  export default {
    name: 'Member',
    data() {
      // 邮箱校验
      let validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入电话号码'));
        } else if (!(/^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/
          .test(value))) {
          callback(new Error("请输入正确的邮箱"));
        } else {
          callback()
        }
      }
      // 电话号码校验
      let validatePhone = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入电话号码'));
        } else if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(value))) {
          callback(new Error("手机号码有误，请重填"));
        } else {
          callback()
        }
      }

      return {
        //  用户控制查看密码弹框的打开与关闭
        managerVisable: false,
        // 存储被查看用户的id
        findId: '',
        // 存储被查看用户密码
        findUserPassword: '',
        //存储管理员数据
        manager: {
          managerPassword: ''
        },
        //加载
        loading: true,
        //校验
        rules: {
          nickname: [{
            required: true,
            message: '请填写昵称',
            trigger: 'blur'
          }],
          sex: [{
            required: true,
            message: '请选择性别',
            trigger: 'change'
          }],
          phone: [{
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }],
          birthday: [{
            required: true,
            trigger: 'blur',
            message: '请选择出生日期'
          }],
          email: [{
            required: true,
            trigger: 'blur',
            validator: validateEmail
          }]
        },
        // 日期选择相关
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        // 弹窗标题
        title: '',
        //查询条件及翻页
        setPageInfo: {
          currentPage: 1,
          pageSize: 5,
          nickname: ''
        },
        //存储查询数据信息
        pageInfo: {

          // 总页数
          totalPage: '',
          // 总记录数
          totalCount: 0
        },
        formLabelWidth: '120px',
        // 控制添加框的展示
        dialogFormVisible: false,
        //接受后端数据
        tableData: [],
        //存储弹出表单数据
        addData: {},
        currentEditMemberInfo: {}, //用于存储当前点击修改时信息
        // 用于存储被选中的行的信息
        multipleSelection: []
      }
    },
    methods: {
      /*确认管理员输入的密码*/
      findPasswordConfirm() {
        if (!this.manager.managerPassword) return this.$message({
          message: '请输入管理员密码',
          type: 'warning'
        })
        let obj = {
          id: this.getUserInfo.id,
          password: this.manager.managerPassword
        }
        this.$axios.get('/ManagerServlet?method=confirmManager', {
          params: obj
        }).then(
          res => {
            if (res.data.code === 200) {
              this.emitPassword()
              setTimeout(() => {
                this.managerVisable = false
              }, 200)
            } else if (res.data.code === 111) {
              this.$message('密码错误')
            }
          }
        )
      },
      /*文件上传前的钩子，对类型进行校验*/
      beforeAvatarUpload(file) {
        const isJPG = file.type.indexOf('image') >= 0 ? true : false;
        if (!isJPG) {
          this.$message.error('只能上传图片!');
        }
      },
      // 文件上传时的钩子
      handleAvatarSuccess(res, file) {
        console.log('res', res)
        this.addData.avater = res.data.filePath
      },
      // 文件移除时的钩子
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      // 点击已 上传文件时的钩子
      handlePictureCardPreview(file) {
        console.log('url', file.url)
        this.addData.avater = file.url;
        this.dialogVisible = true;
      },
      // 文件上传超出限制时的钩子
      handleExceed(files, fileList) {
        this.$message('只能上传一个头像哦!')
      },
      // 处理显示的性别
      formatterSex(rows, column) {
        // 1表示男，0表示女，存储数据库中的类型为int类型0或1
        if (rows.sex !== 0 && rows.sex !== 1) return '未知'
        return rows.sex === 1 ? "男" : "女";
      },
      // 处理显示的禁用状态
      formatterIsDisable(rows, column) {
        // 1表示禁用，0表示可用，存储数据库中的类型为int类型0或1
        return rows.isDisable === 1 ? "禁用" : "可用";
      },
      // 重置密码
      resetPassword(row) {
        this.$confirm('此操作将重置该用户的密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          member.reset(row.memberId)
          this.$message({
            type: 'success',
            message: '密码已重置为：123456'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 弹窗校验
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.updateMember()
          } else {
            this.$message('请正确填写')
            return false;
          }
        });
      },
      //编辑按钮
      handleChange(row) {
        this.dialogFormVisible = true
        this.title = '编辑'
        console.log('row', row)
        // 每次编辑or添加前将之前残留的数据清除
        this.addData = {
          memberId: '',
          avater: '',
          nickname: '',
          sex: '',
          phone: '',
          email: '',
          sign: '',
          localtion: '',
          birthday: '',
          isDisable: '',
          password: '',
        }
        this.currentEditMemberInfo = row //用于更新数据时直接进行前端更新
        this.addData = {
          ...this.currentEditMemberInfo
        }
      },
      // 添加or编辑
      updateMember() {
        if (this.title === '添加') {
          // 时间格式处理
          this.addData.birthday = formatDate(this.addData.birthday)
          member.add(this.addData)
            .then(
              response => {
                if (response.data.code === 200) {
                  this.$notify({
                    title: '成功',
                    message: '插入成功',
                    type: 'success'
                  });
                  this.dialogFormVisible = false
                  this.loadMember()
                } else if (response.data.code === 111) {
                  this.$message('用户名已存在')
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
            )
        } else if (this.title === '编辑') {
          this.addData.birthday = formatDate(this.addData.birthday)
          this.addData.createTime = formatDate(this.addData.createTime)
          this.addData.updateTime = formatDate(this.addData.updateTime)

          member.update(this.addData)
            .then(
              response => {
                if (response.data.code === 200) {
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success'
                  });
                  this.loadMember()
                } else if (response.data.code === 111) {
                  this.$message('要修改为的用户名已存在')
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
            )
        }
      },
      //删除单行
      handleDeleteRow(row) {
        this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          //删除关键代码
          setTimeout(() => {
            member.handleDeleteRow(row.memberId)
              .then(
                response => {
                  this.loadMember()
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                }
              )
          }, 200)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //查询
      onSubmit() {
        this.loading = true
        this.loadMember()
      },
      //添加按钮
      handleAdd() {
        this.dialogFormVisible = true
        this.title = '添加'
        // 每次编辑or添加前将之前残留的数据清除
        this.addData = {
          avater: '',
          nickname: '',
          sex: '',
          phone: '',
          email: '',
          sign: '',
          localtion: '',
          birthday: '',
          isDisable: '',
        }
      },
      //批量删除
      handleDelete() {

        this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          if (this.multipleSelection.length === 0) return this.$message('请选择需要删除的行')
          // 用于存储选择行的id
          let id = []
          this.multipleSelection.forEach(data => {
            id.push(
              data.memberId
            )
          })
          this.loading = true
          member.deleteByIdS(id)
            .then(
              response => {
                this.loadMember()
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success'
                });
              }
            ).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        })
      },
      // 修改每页显示数量
      handleSizeChange(val) {
        this.loading = true
        this.setPageInfo.pageSize = val
        this.loadMember()
      },
      // 翻页
      handleCurrentChange(val) {
        this.loading = true
        this.setPageInfo.currentPage = val
        this.loadMember()
      },
      // 初始化表格
      async loadMember() {
        await member.loadMember(this.setPageInfo.currentPage, this.setPageInfo.pageSize, this.setPageInfo.nickname)
          .then(response => {
            response.data.data.list.forEach(data => {
              data.birthday = format(data.birthday)
              data.createTime = formatDate(data.createTime)
              data.updateTime = formatDate(data.updateTime)
            })

            this.tableData = response.data.data.list
            this.pageInfo.totalCount = response.data.data.total - 0
            this.pageInfo.totalPage = response.data.data.pages

            if (this.tableData.length === 0 && this.setPageInfo.currentPage !== 1) {
              this.setPageInfo.currentPage--
              this.loadMember()
            } else {
              this.loading = false
            }
          })
        // this.loading = false
      },
      //当选择项发生变化时会触发该事件
      handleSelectionChange(val) {
        console.log(val)
        this.multipleSelection = val;
      }
    },
    mounted() {
      this.loadMember()
    },
    computed: {
      ...mapGetters({
        getUserInfo: 'getUserInfo'
      })
    },
  }

</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

</style>
